package com.vend.common.retrofithttp;
import com.vend.common_lib.retrofithttp.RetrofitHttpManager
import retrofit2.Call
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import java.util.ArrayList

/**
 * Created by glendal on 2022/01/13.
 * 创建一个工具类方便请求的处理
 */
abstract class AbsNetWork<T> {
    var mApiService: T? = null
    private val mCalls: MutableList<Call<*>> = ArrayList()
    constructor() {
        if (getAPIService() != null) {
            val finalService = RetrofitHttpManager.instance.create(getAPIService())
//            mApiService = finalService
            //二次代理
            mApiService = Proxy.newProxyInstance(
                getAPIService()!!.classLoader, arrayOf<Class<*>?>(getAPIService())
            ) { proxy: Any?, method: Method, args: Array<Any?> ->
                // If the method is a method from Object then defer to normal invocation.
                val o = method.invoke(finalService, *args)
                if (o is Call<*>) {
                    mCalls.add(o)
                }
                o
            } as T
        }
    }

    /**
     * 界面退出时候必须调用该类
     */
    open fun cancelNetwork() {
        for (call in mCalls) {
            //取消任务
            if (!call.isCanceled) {
                call.cancel()
            }
        }
    }

    /**
     * 获取APISevice类
     *
     * @return
     */
    protected abstract fun getAPIService(): Class<T>

}